package jp.sinya.register.web.servlet;

import jp.sinya.register.bean.User;
import jp.sinya.register.constants.Constants;
import jp.sinya.register.service.UserService;
import jp.sinya.register.util.CommonUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        UserService service = new UserService();
        User user = CommonUtils.toBean(req.getParameterMap(), User.class);

        try {
            User loginUser = service.login(user);
            req.getSession().setAttribute(Constants.SESSION_USER, loginUser);
            resp.sendRedirect(req.getContextPath() + "/success.jsp");

        } catch (Exception e) {
            req.setAttribute(Constants.ERROR_MSG, e.getMessage());
            req.setAttribute(Constants.USER_MSG, user);
            req.getRequestDispatcher("/login.jsp").forward(req, resp);
        }
    }
}
